from flask import Blueprint, request, jsonify
import logging

logger = logging.getLogger(__name__)
from models.user import User
from models.card import Card
from models.deposit import Deposit
from models.transaction import Transaction
from utils.database import db

admin_bp = Blueprint('admin', __name__)

# 客户管理
@admin_bp.route('/customers', methods=['GET'])
def get_customers():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    search = request.args.get('search', '').strip()
    
    query = User.query
    
    if search:
        query = query.filter(
            (User.customer_name.like(f'%{search}%')) |
            (User.pid.like(f'%{search}%')) |
            (User.telephone.like(f'%{search}%'))
        )
    
    pagination = query.paginate(page=page, per_page=per_page)
    customers = pagination.items
    
    return jsonify({
        'success': True,
        'customers': [{
            'id': c.customer_id,
            'name': c.customer_name,
            'pid': c.pid,
            'telephone': c.telephone,
            'address': c.address
        } for c in customers],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': page
    })

@admin_bp.route('/customers', methods=['POST'])
def add_customer():
    data = request.get_json()
    
    # 验证数据
    required_fields = ['name', 'pid', 'telephone']
    for field in required_fields:
        if field not in data or not data[field].strip():
            return jsonify({'success': False, 'message': f'缺少必填字段: {field}'}), 400

    # 验证身份证格式
    if len(data['pid']) != 18:
        return jsonify({'success': False, 'message': '身份证号码必须为18位'}), 400

    # 验证手机号格式
    if not data['telephone'].isdigit() or len(data['telephone']) != 11:
        return jsonify({'success': False, 'message': '手机号必须为11位数字'}), 400

    try:
        new_customer = User(
            customer_name=data['name'],
            pid=data['pid'],
            telephone=data['telephone'],
            address=data.get('address', ''),
            password=data.get('password', '888888')  # 默认密码
        )

        db.session.add(new_customer)
        db.session.commit()

        return jsonify({'success': True, 'message': '客户添加成功'})
    except Exception as e:
        db.session.rollback()
        logger.error(f'添加客户失败: {str(e)}')
        return jsonify({'success': False, 'message': '添加客户失败: 数据库错误'}), 500

# 银行卡管理、存款业务管理、交易管理等其他路由...
# 银行卡管理
@admin_bp.route('/cards', methods=['GET'])
def get_cards():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '').strip()

        query = Card.query

        if search:
            query = query.join(User).filter(
            (Card.card_id.like(f'%{search}%')) |
            (User.customer_name.like(f'%{search}%'))
        )

        pagination = query.paginate(page=page, per_page=per_page)
        cards = pagination.items

        return jsonify({
            'success': True,
            'cards': [{
                'id': c.card_id,
                'customer_id': c.customer_id,
                'cur_id': c.cur_id,
                'saving_id': c.saving_id,
                'open_date': c.open_date.strftime('%Y-%m-%d'),
                'open_money': float(c.open_money),
                'balance': float(c.balance),
                'is_report_loss': c.is_report_loss
            } for c in cards],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        })
    except Exception as e:
        logger.error(f"获取银行卡信息失败: {e}")
        return jsonify({'success': False, 'message': '获取银行卡信息失败'}), 500

@admin_bp.route('/cards', methods=['POST'])
def add_card():
    try:
        data = request.get_json()
        new_card = Card(
            card_id=data['card_id'],
            cur_id=data['cur_id'],
            saving_id=data['saving_id'],
            open_date=data['open_date'],
            open_money=data['open_money'],
            balance=data['open_money'],
            password=data['password'],
            is_report_loss=data.get('is_report_loss', '0'),
            customer_id=data['customer_id']
        )

        db.session.add(new_card)
        db.session.commit()

        return jsonify({'success': True, 'message': '银行卡添加成功'})
    except Exception as e:
        logger.error(f"添加银行卡失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '添加银行卡失败'}), 500

@admin_bp.route('/cards/<string:card_id>', methods=['PUT'])
def edit_card(card_id):
    try:
        data = request.get_json()
        card = Card.query.get(card_id)
        if not card:
            return jsonify({'success': False, 'message': '银行卡不存在'}), 404

        card.cur_id = data.get('cur_id', card.cur_id)
        card.saving_id = data.get('saving_id', card.saving_id)
        card.open_date = data.get('open_date', card.open_date)
        card.open_money = data.get('open_money', card.open_money)
        card.balance = data.get('balance', card.balance)
        card.password = data.get('password', card.password)
        card.is_report_loss = data.get('is_report_loss', card.is_report_loss)
        card.customer_id = data.get('customer_id', card.customer_id)

        db.session.commit()
        return jsonify({'success': True, 'message': '银行卡信息更新成功'})
    except Exception as e:
        logger.error(f"更新银行卡信息失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '更新银行卡信息失败'}), 500

@admin_bp.route('/cards/<string:card_id>', methods=['DELETE'])
def delete_card(card_id):
    try:
        card = Card.query.get(card_id)
        if not card:
            return jsonify({'success': False, 'message': '银行卡不存在'}), 404

        db.session.delete(card)
        db.session.commit()
        return jsonify({'success': True, 'message': '银行卡删除成功'})
    except Exception as e:
        logger.error(f"删除银行卡失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '删除银行卡失败'}), 500
    
    # 存款业务管理
@admin_bp.route('/deposits', methods=['GET'])
def get_deposits():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '').strip()

        query = Deposit.query

        if search:
            query = query.filter(
                (Deposit.saving_name.like(f'%{search}%'))
            )

        pagination = query.paginate(page=page, per_page=per_page)
        deposits = pagination.items

        return jsonify({
            'success': True,
            'deposits': [{
                'id': d.saving_id,
                'name': d.saving_name,
                'descrip': d.descrip
            } for d in deposits],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        })
    except Exception as e:
        logger.error(f"获取存款业务信息失败: {e}")
        return jsonify({'success': False, 'message': '获取存款业务信息失败'}), 500

@admin_bp.route('/deposits', methods=['POST'])
def add_deposit():
    try:
        data = request.get_json()
        new_deposit = Deposit(
            saving_name=data['saving_name'],
            descrip=data.get('descrip', '')
        )

        db.session.add(new_deposit)
        db.session.commit()

        return jsonify({'success': True, 'message': '存款业务添加成功'})
    except Exception as e:
        logger.error(f"添加存款业务失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '添加存款业务失败'}), 500

@admin_bp.route('/deposits/<int:deposit_id>', methods=['PUT'])
def edit_deposit(deposit_id):
    try:
        data = request.get_json()
        deposit = Deposit.query.get(deposit_id)
        if not deposit:
            return jsonify({'success': False, 'message': '存款业务不存在'}), 404

        deposit.saving_name = data.get('saving_name', deposit.saving_name)
        deposit.descrip = data.get('descrip', deposit.descrip)

        db.session.commit()
        return jsonify({'success': True, 'message': '存款业务信息更新成功'})
    except Exception as e:
        logger.error(f"更新存款业务信息失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '更新存款业务信息失败'}), 500

@admin_bp.route('/deposits/<int:deposit_id>', methods=['DELETE'])
def delete_deposit(deposit_id):
    try:
        deposit = Deposit.query.get(deposit_id)
        if not deposit:
            return jsonify({'success': False, 'message': '存款业务不存在'}), 404

        db.session.delete(deposit)
        db.session.commit()
        return jsonify({'success': True, 'message': '存款业务删除成功'})
    except Exception as e:
        logger.error(f"删除存款业务失败: {e}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '删除存款业务失败'}), 500
    
    # 交易管理
@admin_bp.route('/transactions', methods=['GET'])
def get_transactions():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '').strip()

        query = Transaction.query

        if search:
            query = query.filter(
                (Transaction.card_id.like(f'%{search}%')) |
                (Transaction.trade_type.like(f'%{search}%'))
            )

        pagination = query.paginate(page=page, per_page=per_page)
        transactions = pagination.items

        return jsonify({
            'success': True,
            'transactions': [{
                'id': t.id,
                'trade_date': t.trade_date.strftime('%Y-%m-%d %H:%M:%S'),
                'trade_type': t.trade_type,
                'card_id': t.card_id,
                'trade_money': float(t.trade_money),
                'remark': t.remark
            } for t in transactions],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        })
    except Exception as e:
        logger.error(f"获取交易信息失败: {e}")
        return jsonify({'success': False, 'message': '获取交易信息失败'}), 500
